package com.shuqing.download.engine.distribute.dispatch.monitor.strategy;

import cn.hutool.core.util.StrUtil;
import com.shuqing.download.engine.DownLoadTaskDto;
import com.shuqing.download.engine.constants.EventEnum;
import com.shuqing.download.engine.distribute.dispatch.TaskContext;
import com.shuqing.download.engine.distribute.dispatch.monitor.Event;
import com.shuqing.download.model.DownLoadLog;
import com.shuqing.download.service.owner.DownLoadLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 事件默认处理机制
 * @author wangshuqing
 * @date 2023/3/4 18:36
 */
@Slf4j
@Component
public class DefaultEventHandler implements Event {
    @Autowired
    private DownLoadLogService downLoadLogService;

    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    @Override
    public void discover(TaskContext context, EventEnum eventEnum, Boolean success, String errorMsg,Object... args) {
        DownLoadTaskDto task=context.getTask();
        DownLoadLog downLoadLog=new DownLoadLog();
        downLoadLog.setCreateTime(new Date());
        int maxLength=800;
        if(StrUtil.isNotBlank(errorMsg) && errorMsg.length()>maxLength){
            downLoadLog.setErrorMsg(errorMsg.substring(0,maxLength));
        }else{
            downLoadLog.setErrorMsg(errorMsg);
        }
        downLoadLog.setSequenceNumber(task.getRetryCount());
        String markMsg= StrUtil.format(eventEnum.getFormat(),args);
        downLoadLog.setMarkMsg(markMsg);
        int successFlag= success ? 1 : 0;
        downLoadLog.setSuccessFlag(successFlag);
        downLoadLog.setTaskId(task.getId());
        downLoadLog.setUpdateTime(downLoadLog.getCreateTime());
        downLoadLog.setConsumeTimes(context.getLastConsumeTime());
        downLoadLogService.save(downLoadLog);
    }

}
